#------------------------------------
# PROGRAM SETUP
#------------------------------------

here::i_am("./3_figures.R")

library(here)
library(tidyverse)
library(haven)
library(ggpattern)

#------------------------------------
# FIGURE B1
#------------------------------------

# READ IN DATA

swingstate_panel <- read_csv(here("intermediate","swingstate_panel.csv"))
senatebalance_ts <- read_dta(here("intermediate","senatetightness_tsanalysis.dta"))

# CREATE DATASET

swingstate_senatebalance <- left_join(swingstate_panel,
                                      senatebalance_ts %>% select(year, starts_with('tightsenate')),
                                      by = 'year') %>%
  mutate(balancedsenate = tightsenate6,
         startyear = if_else(balancedsenate == 1, year - 0.5, NA),
         endyear = if_else(balancedsenate == 1, year + 0.5, NA))

# CREATE FIGURE B1

states_balancedsenate4 <- ggplot() +
  geom_tile_pattern(data = swingstate_senatebalance,
                    mapping = aes(year, state, fill = swingstate, pattern = as.factor(balancedsenate)),
                    color = "black", linewidth = 0.1,
                    pattern_color = NA,
                    pattern_fill = "black",
                    pattern_angle = 45,
                    pattern_density = 0.2,
                    pattern_spacing = 0.035,
                    pattern_key_scale_factor = 1) +
  scale_pattern_manual(values = c("none", "stripe")) +
  scale_fill_gradient(low = "white", high = "darkgray") +
  labs(x = "Year",
       y = "State") +
  scale_x_continuous(position = "top",
                     breaks = c(1994,1996,1998,2000,2002,2004,2006,2008,2010,2012,
                                2014,2016,2018,2020)) +
  scale_y_discrete(limits = unique(rev(swingstate_panel$state))) +
  theme_minimal() +
  theme(legend.position = "none",
        axis.text = element_text(size = 8),
        axis.text.x = element_text(angle = 45, vjust = 0.5, hjust = 0),
        axis.text.y = element_text(hjust = 1,
                                   margin = margin(t = 0, r = -9, b = 0, l = 0, unit = "pt"),
                                   debug = FALSE),
        axis.title = element_blank(),
        plot.background = element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank()) +
  coord_fixed()

ggsave(here("output","figures","fig_swingstatestatus_balancedsenate_panel4.png"),
       device = 'png',
       units = "px",
       height = 2400)

#------------------------------------
# FIGURE B2(a) and (b)
#------------------------------------

rm(list = ls())

# READ IN DATA

raw_data <- read_dta(here("intermediate","senatetightness_tsanalysis.dta"))

# PROCESS TIGHT SENATE

senatetightness <- raw_data %>%
  filter(year >= 1995 & tightsenate6 == 1) %>%
  select(congnum = congress, year) %>%
  group_by(congnum) %>%
  mutate(startyr = min(year), endyr = max(year)) %>%
  ungroup() %>%
  select(congnum, startyr, endyr) %>%
  distinct() %>%
  mutate(startyr = startyr - 0.5,
         endyr = endyr + 0.5)

# CREATE FIGURE B2(a)

tsgraph <-
  ggplot() +
  geom_line(data = raw_data %>% filter(year >= 1995),
            mapping = aes(x = year, y = absvotediff,
                          color = "PresVoteMargin")) +
  geom_rect(data = senatetightness,
            mapping = aes(ymin = 0.05, ymax = 0.2, xmin = startyr, xmax = endyr,
                          fill = "Balanced Senate"),
            alpha = 0.25) +
  scale_color_manual(values = c("PresVoteMargin" = "black")) +
  scale_fill_manual(values = c("Balanced Senate" = "black")) +
  labs(y = "Percent (%)",
       x = "Year",
       color = "Legend") +
  scale_x_continuous(expand = expansion(add = 0.1)) +
  scale_y_continuous(expand = expansion(0),
                     labels = function(x) 100*x) +
  theme_bw() +
  theme(
    axis.text.x = element_text(size = 10),
    axis.text.y = element_text(size = 10),
    axis.title.x = element_blank(),
    axis.ticks.length.y = unit(-1.1, 'mm'),
    legend.title = element_blank(),
    legend.position = "bottom")

ggsave(here("output","figures","fig_ts_votemargin_tightsenates.png"),
       tsgraph,
       width = 2400,
       height = 1600,
       units = 'px')

# CREATE FIGURE B2(b)

tsgraph <-
  ggplot() +
  geom_line(data = raw_data %>% filter(year >= 1995),
            mapping = aes(x = year, y = realgdp_gr,
                          color = "Real GDP Growth")) +
  geom_line(data = raw_data %>% filter(year >= 1995),
            mapping = aes(x = year, y = unrate,
                          color = "Unemployment Rate")) +
  geom_rect(data = senatetightness,
            mapping = aes(ymin = -0.05, ymax = 0.15, xmin = startyr, xmax = endyr,
                          fill = "Balanced Senate"),
            alpha = 0.25) +
  scale_color_manual(values = c("Unemployment Rate" = "blue",
                                "Real GDP Growth" = "red")) +
  scale_fill_manual(values = c("Balanced Senate" = "black")) +
  labs(y = "Percent (%)",
       x = "Year",
       color = "Legend") +
  scale_x_continuous(expand = expansion(add = 0.1)) +
  scale_y_continuous(expand = expansion(0),
                     labels = function(x) 100*x) +
  theme_bw() +
  theme(
    axis.text.x = element_text(size = 10),
    axis.text.y = element_text(size = 10),
    axis.title.x = element_blank(),
    axis.ticks.length.y = unit(-1.1, 'mm'),
    legend.title = element_blank(),
    legend.position = "bottom")

ggsave(here("output","figures","fig_ts_unemp_GDP_tightsenates.png"),
       tsgraph,
       width = 2400,
       height = 1600,
       units = 'px')
